package ru.spbu.math.seabattle.client.jms.gui;

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.swing.JFrame;

import ru.spbu.math.seabattle.client.jms.SeaBattleClient;
import ru.spbu.math.seabattle.entity.PlayerID;

public class PlayerListGUI extends JFrame {
	
	private static final long serialVersionUID = 1L;

	private Map<PlayerID, String> playersId2Names = new ConcurrentHashMap<PlayerID, String>();
	
	private PlayerListComponent playerList;
	
	private ExtendedContainer content = new ExtendedContainer(
												this.getContentPane()
											);

	private SeaBattleClient client;
	
	public PlayerListGUI(final SeaBattleClient client) {
		super("(" + client.getName() + ")" + " Player List");
		this.setBounds(Constants.getListFrameRectangle());
		this.setResizable(false);
		
		this.client = client;

		content.setLayout(null);
		
		playerList = new PlayerListComponent(this);
		playerList.setBounds(Constants.getPlayerListRectangle());
		content.add(playerList);
		
		this.setVisible(true);
		
		this.addWindowListener(new WindowListener() {

			@Override
			public void windowClosing(WindowEvent arg0) {
				client.sayGoodbyeToYourServer();
			}

			@Override public void windowActivated(WindowEvent arg0) {}
			@Override public void windowClosed(WindowEvent arg0) {}
			@Override public void windowDeactivated(WindowEvent arg0) {}
			@Override public void windowDeiconified(WindowEvent arg0) {}
			@Override public void windowIconified(WindowEvent arg0) {}
			@Override public void windowOpened(WindowEvent arg0) {}
		});
	}
	
	//to server
	public void onPlayerSelected(PlayerID id) {
		
		client.onPlayerSelected(id);
	}
	
	//to server
	public void onApplicationPut() {
		client.onApplicationPut();
	}
	
	//to server
	public void onApplicationWithdrawn() {
		client.onApplicationWithdrawn();
	}

	public void onPlayerJoined(PlayerID id, String name) {

		if (id.equals(client.getPlayerID())) {
			playerList.disable();
		}
		
		playersId2Names.put(id, name);
		playerList.addPlayer(name, id);
	}
	
	public void onPlayerLeft(PlayerID id) {
		
		if (id.equals(client.getPlayerID())) {
			playerList.enable();
		}
		playerList.removePlayer(playersId2Names.get(id));
		playersId2Names.remove(id);
	}
}
